/**
 * Created by sunidea on 2017/3/13/013.
 */
// window.location.protocol === 'http:' && window.location.replace(window.location.href.replace('http:', 'https:'))
// var webapi = /xinglongdayuan.com/i.test(location.host) ? "//api.one-stop.xinglongdayuan.com" : "//api.one-stop.xlgoo.net";

// window.location.protocol === 'http:' && window.location.replace(window.location.href.replace('http:', 'http:'))
var webapi = "//api.one-shake.xinglongdayuan.com";

$(function(){
    try{
        FastClick.attach(document.body);
        template.helper('CYutils', CYutils);
    }catch(f){}
});

var CYutils = {};
/**
 * API
 */
if (typeof mid === 'undefined'){
    var mid = 'DJEHBSUAAY';
}
CYutils.API = {
    OrderUrl:{
        get_store_positon: webapi + "/ol/coupon/OutletConponList/" + mid,
        get_getshopnav: webapi + "/ol/eshop/getShopNav/" + mid,//nav
        get_getshopad: webapi + "/ol/eshop/getShopAd/" + mid,//ad
        get_getbanner: webapi + "/ol/eshop/getShopBanner/" + mid,//banner
        categoryCouponInfo: webapi + "/ol/coupon/categoryCouponInfo/" + mid,//优惠券分类
        categoryCouponInfoByParentid: webapi + "/ol/coupon/categoryCouponInfoByParentid/" + mid//优惠券下级分类
    },
    Member:{
        fetchMemberInfo_xlapp: webapi+'/ol/xlapp/fetchMemberInfo/'+mid, // 判断是否绑定过大院卡
        fetchMemberInfo_xlclerk: webapi+'/ol/xlclerk/fetchMemberInfo/'+mid, // 判断是否绑定过大院卡
        get_mycoupon: webapi + '/ol/member_coupon/MyCoupon/' + mid, //会员卡券包列表
        coupon_log_details: webapi+'/ol/coupon/coupon_log_details/'+mid, //会员卡券包二维码
        coupon_verify_line: webapi+'/ol/coupon/coupon_verify_line/'+mid, //会员卡券包核销
        get_order_coupon_details: webapi+'/ol/member_coupon/tryOrderList/'+mid, //优惠券订单详情
        get_available_goods: webapi+'/ol/eshop_list/eshop_list/'+mid ,//查看优惠劵可用商品
        del_coupon: webapi+'/ol/eshop_coupon/DelCoupon/'+mid, //删除优惠劵
        Index: {
            memberordernum: webapi + '/ol/xlapp/memberordernum/' + mid, // 订单数
            countKindCoupon: webapi + '/ol/xlapp/countKindCoupon/' + mid, // 订单总数量
            getnews_along: webapi + "/ol/eshop/getnews_along/" + mid, // 大院广播
            // memberordernum: webapi + "/ol/member_order/memberordernum/" + mid,//订单数
            // fetchMemberInfo: webapi + "/ol/xlapp/fetchMemberInfo/" + mid,//会员顶部基本信息
            fetchPoint: webapi + "/ol/xlapp/fetchPoint/" + mid,//会员积分
            GetSaleMast: webapi + "/ol/xlapp/GetSaleMast/" + mid,//会员消费记录
            GetSaleMastDetail: webapi + "/ol/xlapp/GetSaleMastDetail/" + mid,//会员消费记录详细
            get_ewms: "/app/public/DKFQRCODEURL",//获取客服二维码
            // countKindCoupon: webapi + "/ol/member_coupon/countKindCoupon/" + mid // 订单总数量
            dsfadf: webapi + "/ol/xlapp/GetSaleMast/" + mid //
        },
        Wallet: { // 钱包
            xl_balance_open: webapi+'/ol/xl_balance/open/'+mid, // 开通
            xl_balance_bind: webapi+'/ol/xl_balance/bind/'+mid, // 绑定
            xl_balance_unbind: webapi+'/ol/xl_balance/unbind/'+mid, // 解绑
            xl_balance_getbalance: webapi+'/ol/xl_balance/getbalance/'+mid, // 获取钱包页数据 （包括可用金额）
            xl_xlapp_getXlCardList: webapi+'/ol/xlapp/getXlCardList/'+mid, // 充值页列表数据
            xl_xlCardRechanges: webapi+'/ol/xlmembercard/xlCardRechanges/'+mid, // 充值成功
            xl_xlapp_cardBalanceDetail: webapi+'/ol/xlapp/cardBalanceDetail/'+mid, // 获取HiPay消费明细
            xl_gold_incentive_getsalelist: webapi + '/ol/gold_incentive/getsalelist/' + mid, // 获取HiPay消费明细
            xl_gold_incentive_getsaledetail: webapi + '/ol/gold_incentive/getsaledetail/' + mid, // 消费明细详情
            xl_xlapp_xlApplyDealBarcode: webapi+'/ol/xlapp/xlApplyDealBarcode/'+mid, // 获取条形码
            xl_pay_addpaycard: webapi+'/ol/pay/addpaycard/'+mid, // 支付获取payid
            xl_pay_getPayType: webapi+'/ol/pay/getPayType/'+mid, // 获取支付方式
            xl_appwxpay_sign: webapi+'/ol/appwxpay/sign/'+mid, // 获取签名
            xl_xlmembercard_getXlCardRechargeRecord: webapi+'/ol/xlmembercard/getXlCardRechargeRecord/'+mid, // 获取充值明细
            xl_xlmembercard_modPayPass: webapi+'/ol/xlmembercard/modPayPass/'+mid, // 修改支付密码保存
            xl_balance_getclockinfo: webapi+'/ol/xl_balance/getclockinfo/'+mid, // 锁定金额列表
            xl_send_sms_sendPhoneCode: webapi+'/ol/send_sms/sendPhoneCode/'+mid, // 发送验证码
            xl_scanpay_success: 'https://wss.xinglongdayuan.com:2120', // 付款成功
        }
    }
};
/**
 * 对象类型判断
 * isString(obj)
 * @return Boolean
 */
['String', 'Function', 'Array', 'Number', 'RegExp', 'Object', 'Date'].forEach( function (v) {
    CYutils['is' + v] = function (obj) {
        return Object.prototype.toString.apply(obj) === '[object ' + v + ']';
    }
});

/**
 *
 * @param param
 * {
 * type: true, // 是否带0
 * time: new Date('2017/07/08'), // 日期
 * showtime:"true" // 是否显示时间
 * }
 * @returns {*}
 */
CYutils.formatTimestamp = function(param) {
    var d = new Date();
    d.setTime(param && param.time || d);
    var symble = param && param.symble ? param.symble : '-';
    var type = param && !!param.type;
    var showtime = param && param.showtime || false;
    var datetime = null;
    var x = d.getFullYear() + symble + (d.getMonth() < 9 ? "0" : "") + (d.getMonth() + 1) + symble + (d.getDate() < 10 ? "0" : "") + d.getDate();
    var y = (d.getHours() < 10 ? " 0" : " ") + d.getHours() + ":" + (d.getMinutes() < 10 ? "0" : "") + d.getMinutes() + ":" + (d.getSeconds() < 10 ? "0" : "") + d.getSeconds();

    if(showtime) {
        datetime = x + y;
    } else {
        datetime = x;
    }

    if(type){
        var _reg = new RegExp('\\'+symble+'0(\\d{1})', 'g');
        datetime = datetime.replace(_reg, symble + '$1')
        // .replace(/\:0(\d{1})/g, ':$1')
    }

    return datetime;
};

/**
 * 将数值截取后2位小数,格式化成金额形式
 *
 * @param num 数值(Number或者String)
 * @param flag 布尔(true或者false) true 去掉多余0
 * @return 金额格式的字符串,如'1,234,567.45'
 * @type String
 */
CYutils.formatCurrency = function(num, flag) {
    num = num.toString().replace(/\$|\,/g, '');
    if(isNaN(num))
        num = "0";
    var sign = (num == (num = Math.abs(num)));
    num = Math.floor(CYutils.Fmul(num, 100));
    var cents = num % 100;
    var centsi = num % 100 == 0 ? '' : String(num % 100).indexOf('0') == 1 ? '.' + String(num % 100).substr(0, 1) : '.' + String(num % 100);
    num = Math.floor(num / 100).toString();
    if(cents < 10)
        cents = "0" + cents;
    for(var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' +
            num.substring(num.length - (4 * i + 3));
    var result = flag ? (((sign) ? '' : '-') + num + centsi) : (((sign) ? '' : '-') + num + '.' + cents);
    return result;
};
//格式化金额整数
CYutils.formatIntCurrency = function(num) {
    num = parseInt(num.toString().replace(/\$|\,/g, '')).toString();
    if(isNaN(num))
        num = "0";
    for(var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' +
            num.substring(num.length - (4 * i + 3));
    return num;
};
//修复JS浮点的加减乘除运算 Fadd加 Fsub减 Fmul乘 Fdiv除
CYutils.Fadd = function(a, b) {
    var c, d, e;
    try {
        c = a.toString().split(".")[1].length;
    } catch(f) {
        c = 0;
    }
    try {
        d = b.toString().split(".")[1].length;
    } catch(f) {
        d = 0;
    }
    return e = Math.pow(10, Math.max(c, d)), (CYutils.Fmul(a, e) + CYutils.Fmul(b, e)) / e;
};
CYutils.Fsub = function(a, b) {
    var c, d, e;
    try {
        c = a.toString().split(".")[1].length;
    } catch(f) {
        c = 0;
    }
    try {
        d = b.toString().split(".")[1].length;
    } catch(f) {
        d = 0;
    }
    return e = Math.pow(10, Math.max(c, d)), (CYutils.Fmul(a, e) - CYutils.Fmul(b, e)) / e;
};

CYutils.Fmul = function(a, b) {
    var c = 0,
        d = a.toString(),
        e = b.toString();
    try {
        c += d.split(".")[1].length;
    } catch(f) {}
    try {
        c += e.split(".")[1].length;
    } catch(f) {}
    return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
};

CYutils.Fdiv = function(a, b) {
    var c, d, e = 0,
        f = 0;
    try {
        e = a.toString().split(".")[1].length;
    } catch(g) {}
    try {
        f = b.toString().split(".")[1].length;
    } catch(g) {}
    return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), CYutils.Fmul(c / d, Math.pow(10, f - e));
};
//转几位小数点（按位数截取），带后缀（单位）GHutils.toFixed(10000,4,"元") = 10000.0000元
CYutils.toFixeds = function(numb, digital, suffix) {
    var _digital = digital ? digital : 0;
    var fixed = 1;
    for(var i = 0; i < _digital; i++) {
        fixed = fixed * 10;
    }

    if(numb == undefined || numb.length == 0) {
        return "--";
    } else {
        var numb = CYutils.Fmul(Number(numb), fixed);
        return(parseInt(numb) / fixed).toFixed(_digital) + (suffix ? suffix : "");
    }
};

/**************************懒加载*************************************/
CYutils.lazyload = function(){
    var num,img,n=0;
    function lazyload() { //监听页面滚动事件
        num = $('.turn_lazy').length;
        img = $(".turn_lazy");
        var seeHeight = document.documentElement.clientHeight; //可见区域高度
        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; //滚动条距离顶部高度
        for (var i = 0; i < num; i++) {
            if (jQuery(img[i]).offset().top < seeHeight + scrollTop) {
                if (img[i].getAttribute("src") == "/static/userTemplate/eshop/s021/index/images/defu.jpg" || img[i].getAttribute("src") == "/static/userTemplate/eshop/s021/index/images/defu100.jpg") {
                    img[i].src = img[i].getAttribute("data-src");
                    jQuery(img[i]).removeClass('turn_lazy');
                    img[i].removeAttribute('data-src');
                }
                // n = i + 1;
            }
        }
    }
    $(function(){
        // 实际想绑定在 scroll 事件上的 handler

        //var n = 0; //存储图片加载到的位置，避免每次都从第一张图片开始遍历
        lazyload(); //页面载入完毕加载可是区域内的图片
        window.onscroll = lazyload;
    });
    function throttle(fun, delay, time) {
        var timeout,
            startTime = new Date();
        return function() {
            var context = this,
                args = arguments,
                curTime = new Date();
            clearTimeout(timeout);
            // 如果达到了规定的触发时间间隔，触发 handler
            if (curTime - startTime >= time) {
                fun.apply(context, args);
                startTime = curTime;
                // 没达到触发间隔，重新设定定时器
            } else {
                timeout = setTimeout(fun, delay);
            }
        };
    }
    // 采用了节流函数
    // jQuery(window).on('scroll',throttle(lazyload,200,500));
    window.addEventListener('scroll',throttle(lazyload,200,500));
};
/**************************懒加载*************************************/
/**************************querystring开始*************************************/
CYutils.QueryString = function () {
    var QueryString = {};
    // The escape/unescape function used by stringify/parse, provided so that it
    // could be overridden if necessary. This is important in cases where
    // non-standard delimiters are used, if the delimiters would not normally be
    // handled properly by the built-in (en|de)codeURIComponent functions.
    QueryString.escape = encodeURIComponent;

    QueryString.unescape = function (s) {
      // The + character is interpreted as a space on the server side as well as
      // generated by forms with spaces in their fields.
      return decodeURIComponent(s.replace(/\+/g, ' '));
    };
    /**
     * Serialize an object to a query string. Optionally override the default
     * separator and assignment characters.
     *
     * stringify({foo: 'bar'})
     *   // returns 'foo=bar'
     *
     * stringify({foo: 'bar', baz: 'bob'}, ';', ':')
     *   // returns 'foo:bar;baz:bob'
     */
    QueryString.stringify = function (obj, sep, eq, arrayKey) {
      if (!isPlainObject(obj)) return '';

      sep = sep || '&';
      eq = eq || '=';
      arrayKey = arrayKey || false;

      var buf = [],
        key, val;
      var escape = QueryString.escape;

      for (key in obj) {
        if (!hasOwnProperty.call(obj, key)) continue;

        val = obj[key];
        key = QueryString.escape(key);

        // val is primitive value
        if (isPrimitive(val)) {
          buf.push(key, eq, escape(val + ''), sep);
        }
        // val is not empty array
        else if (isArray(val) && val.length) {
          for (var i = 0; i < val.length; i++) {
            if (isPrimitive(val[i])) {
              buf.push(
                key,
                (arrayKey ? escape('[]') : '') + eq,
                escape(val[i] + ''),
                sep);
            }
          }
        }
        // ignore other cases, including empty array, Function, RegExp, Date etc.
        else {
          buf.push(key, eq, sep);
        }
      }

      buf.pop();
      return buf.join('');
    };

    /**
     * Deserialize a query string to an object. Optionally override the default
     * separator and assignment characters.
     *
     * parse('a=b&c=d')
     *   // returns {a: 'b', c: 'c'}
     */
    QueryString.parse = function (str, sep, eq) {
      if (typeof str === 'undefined') {
        str = document.location.search
      }
      var ret = {};

      if (typeof str !== 'string' || trim(str).length === 0) {
        return ret;
      }

      // remove ^?
      str = str.replace(/^\?/, '');

      var pairs = str.split(sep || '&');
      eq = eq || '=';
      var unescape = QueryString.unescape;

      for (var i = 0; i < pairs.length; i++) {

        var pair = pairs[i].split(eq);
        var key = unescape(trim(pair[0]));
        var val = unescape(trim(pair.slice(1).join(eq)));

        var m = key.match(/^(\w+)\[\]$/);
        if (m && m[1]) {
          key = m[1];
        }

        if (hasOwnProperty.call(ret, key)) {
          if (!isArray(ret[key])) {
            ret[key] = [ret[key]];
          }
          ret[key].push(val);
        } else {
          ret[key] = m ? [val] : val;
        }
      }

      return ret;
    };

    // Helpers

    var toString = Object.prototype.toString;
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    var isArray = Array.isArray || function (val) {
      return toString.call(val) === '[object Array]';
    };
    var trim = String.prototype.trim ?
      function (str) {
        return (str == null) ?
          '' :
          String.prototype.trim.call(str);
      } :
      function (str) {
        return (str == null) ?
          '' :
          str.toString().replace(/^\s+/, '').replace(/\s+$/, '');
      };

    /**
     * Checks to see if an object is a plain object (created using "{}" or
     * "new Object()" or "new FunctionClass()").
     */
    var isPlainObject = function (o) {
      /**
       * NOTES:
       * isPlainObject(node = document.getElementById("xx")) -> false
       * toString.call(node):
       *   ie678 === '[object Object]', other === '[object HTMLElement]'
       * 'isPrototypeOf' in node:
       *   ie678 === false, other === true
       */
      return o &&
        toString.call(o) === '[object Object]' &&
        'isPrototypeOf' in o;
    };

    /**
     * If the type of o is null, undefined, number, string, boolean,
     * return true.
     */
    var isPrimitive = function (o) {
      return o !== Object(o);
    };
    return QueryString;
};
CYutils.querystring = CYutils.QueryString();
/**************************querystring结束*************************************/

//获取url参数$.getUrlParam();
CYutils.getUrlParam = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURIComponent(r[2]); return null;
};
/**
 * 获取hash参数
 * @param name
 * @returns {*}
 */
CYutils.getHashParam = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = location.hash.substr(location.hash.indexOf('?')+1).match(reg);
    if (r != null) return decodeURIComponent(r[2]); return null;
};

// 请求验证身份携带cookie
jQuery.ajaxSetup({
    // tpl:$('<div id="loadings">'+
    //     '<div class="loading-3">'+
    //     '<i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i>'+
    //     '</div>'+
    //     '<p style=" padding-top: 20%;font-size: 0.875em;">努力加载中 </p>' +
    //     '</div>'),
    // beforeSend: function(){this.tpl.appendTo('body')},
    // complete: function(){try{this.tpl.remove()}catch(f){}},
    xhrFields: {withCredentials: true}
});
// 相同URL，防止重复提交
CYutils.pendingRequests = {};
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
    var key = options.url;
    // console.log(key);
    if (!CYutils.pendingRequests[key]) {
        CYutils.pendingRequests[key] = jqXHR;
    }else{
        console.log(key);
        jqXHR.abort(); //放弃后触发的提交
        // pendingRequests[key].abort(); // 放弃先触发的提交
    }
    var complete = options.complete;
    options.complete = function(jqXHR, textStatus) {
        CYutils.pendingRequests[key] = null;
        if ($.isFunction(complete)) {
            complete.apply(this, arguments);
        }
    };
});
CYutils.loading = function(){
    $.ajaxSetup({
        tpl: $('<div id="loadingToast" style="opacity: 1; display: block;">' +
            '<div class="weui-mask_transparent"></div>' +
            '<div class="weui-toast">' +
            '<i class="weui-loading weui-icon_toast"></i>' +
            '<p class="weui-toast__content">数据加载中</p>' +
            '</div>' +
            '</div>'),
        beforeSend: function(){this.tpl.appendTo('body')},
        complete: function(){try{this.tpl.remove()}catch(f){}}
    });
};
/**
 * jquery ajax
 * @param url 请求url
 * @param option {Object} 请求需要传送的参数
 * type: String 请求方式 get|post 默认get
 * data: Object 请求数据
 * timeout: Number 超时 默认10秒
 * success error {Function} 成功 失败 回调
 */
CYutils.ajax = function (url, option) {
    var _option = $.extend({}, {
        url: url || '',
        type: 'get',
        dataType: 'json', //服务器返回json格式数据
        data: {},
        onErrorToast: true,
        timeout: 10000,
    }, option || url);
    return $.ajax({
        url: _option.url || url,
        type: _option.type,
        data: _option.data,
        timeout: _option.timeout,

        dataFilter: function (data) {
            return CYutils.isString(data) ? JSON.parse(data) : data
        },
        xhrFields: {
            withCredentials: true
        },
        success: function (data) {
            if (data) {
                if (data.error == 0 || data.Error == 0) {
                    if (_option && CYutils.isFunction(_option.success)) _option.success(data);
                } else {
                    _option.onErrorToast && CYutils.toast(data.Msg);
                }
            }
        },
        error: function () {
            console.log(arguments);
            var _info = arguments[1];
            _option.onErrorToast && _info != 'abort' && CYutils.toast('请求失败');
            if (CYutils.isFunction(_option.error)) _option.error(arguments);
            // try{onError();}catch(f){}
        }
    });
};
/**
 * jquery ajax
 * @param url 请求url
 * @param parameter {Object} 请求需要传送的参数
 * @param onSuccess {Function} 请求成功回调函数
 * @param onError {Function} 请求失败回调
 * @param method {String} 请求方法，默认get
 */
CYutils.load = function (url, parameter, onSuccess, onError, option) {
    var _parameter = $.extend({}, parameter);
    var _onSuccess = CYutils.isFunction(onSuccess) ? onSuccess
        : CYutils.isObject(onSuccess) && CYutils.isFunction(onSuccess.onSuccess) ? onSuccess.onSuccess
            : CYutils.isObject(option) ? option.onSuccess || null
                : null;
    var _onError = CYutils.isFunction(onError) ? onError
        : CYutils.isObject(onSuccess) && CYutils.isFunction(onSuccess.onError) ? onSuccess.onError
            : CYutils.isObject(option) ? option.onError || null
                : null;
    var _option = $.extend({},{method: 'get', onErrorToast: true}, option || onSuccess);
    return $.ajax({
        url: url,
        method: _option.method,
        data: _parameter,
        dataFilter: function(data){
            return CYutils.isString(data) ? JSON.parse(data) : data
        },
        success: function (data) {
            if (data) {
                if (data.Error == 0) {
                    if(CYutils.isFunction(_onSuccess)) onSuccess(data);
                } else if (data.Error == 301) {
                    CYutils.dialog(["温馨提示","请先登录"]);
                    // onSuccess && onSuccess(data);
                } else if(data.Error == 410){
                    CYutils.dialog(["是否进入会员中心",data.Msg],{
                        cancel: true,
                        confirmText:'是',
                        cancelText:'否',
                        onConfirm:function(){
                            if(CYutils.isApp()){
                                if(CYutils.isIOS()){
                                    bridge.send({ Foo:"returnMy"});
                                    return;
                                }else if(CYutils.isAndroid()){
                                    Android.returnMy();
                                    return;
                                }
                            }
                            window.location.href = "/app/member/index";
                        }
                    });
                }else {
                    _option.onErrorToast && CYutils.toast(data.Msg);
                }
            }
        },
        error: function(){
            var _info = arguments[1];
            _option.onErrorToast && _info != 'abort' && CYutils.toast('请求失败');
            if (CYutils.isFunction(_onError)) onError(arguments);
            // try{onError();}catch(f){}
        }
    });
};

/**
 * 百度定位方法封装
 * @param fn()
 * @return _pos
 */
CYutils.getGeoPosition = function(fn){
    var fnGeolocation = function(showPosition){
        var _pos = showPosition;
        CYutils.POS = showPosition;
        if(CYutils.isFunction(fn)){
            fn(_pos)
        }else{
            return _pos
        }
    };
    if(!!sessionStorage.getItem("lat")&&sessionStorage.getItem("lat")!='undefined' && !!sessionStorage.getItem("lng")&&sessionStorage.getItem("lng")!='undefined'){
        fnGeolocation({
            lat:sessionStorage.getItem("lat"),
            lng:sessionStorage.getItem("lng")
        });
    }else{
        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(function(r){
            var _pos = {
                lat:r.point.lat,
                lng:r.point.lng
            };
            if(this.getStatus() == BMAP_STATUS_SUCCESS){
                sessionStorage.setItem("lat", _pos.lat);
                sessionStorage.setItem("lng", _pos.lng);
                fnGeolocation(_pos);
            } else {
                fnGeolocation(_pos);
            }
        },{enableHighAccuracy: true});
    }
};
/**
 * 百度计算距离方法
 * @param lat_b
 * @param lng_b
 * @returns {string} unit: km
 */
CYutils.getAddress = function(lat_b, lng_b){
    var pk = 180 / 3.14169;
    var a1 = CYutils.POS.lat / pk;
    var a2 = CYutils.POS.lng / pk;
    var b1 = lat_b / pk;
    var b2 = lng_b / pk;
    var t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2);
    var t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2);
    var t3 = Math.sin(a1) * Math.sin(b1);
    var tt = Math.acos(t1 + t2 + t3);
    return parseFloat((6366000 * tt) / 1000).toFixed(2);
    // return 6366000 * tt;
};

/**
 * @param arr
 * @param key {String}
 * @param method {String} 1 || 0 排序
 * @returns {*}
 */
CYutils.dataSort = function(arr,key,method){
    if(!CYutils.isArray(arr)){
        console.error('arr is not Array');
        return;
    }
    if(!key){
        console.error('key format error, please check "key"');
        return;
    }
    !CYutils.isString(key)&&console.warn('key is not String');
    !CYutils.isString(method)&&console.warn('method is not String, ascending(default)');
    var result = arr;
    var _m = CYutils.isString(method)&&method=='0'?false:true;
    if(!!arr||arr.length>0){
        result = arr.sort(function(a,b){
            var da = a[key];
            var db = b[key];
            if(_m){ //升序
                if (da > db) {
                    return 1;
                } else if (da < db) {
                    return -1;
                } else {
                    return 0;
                }
            }else{ //降序
                if (db > da) {
                    return 1;
                } else if (db < da) {
                    return -1;
                } else {
                    return 0;
                }
            }
        });
    }
    return result;
};

// App
CYutils.isApp = function(){
    return  CYutils.cookie.get('BDed_third_party_wxweb')==='app'
};
// 微信环境
CYutils.isWeiXin = function(){
    var ua = window.navigator.userAgent.toLowerCase();
    return ua.match(/MicroMessenger/i) == 'micromessenger'
};
// 移动设备
CYutils.isMobileDevice = function(){
    var sUserAgent = navigator.userAgent.toLowerCase();
    var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
    var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
    var bIsMidp = sUserAgent.match(/midp/i) == "midp";
    var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
    var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
    var bIsAndroid = sUserAgent.match(/android/i) == "android";
    var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
    var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
    return bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM
};
// 安卓手机
CYutils.isAndroid = function(){
    var sUserAgent = navigator.userAgent.toLowerCase();
    return sUserAgent.match(/android/i) == "android";
};
// 苹果手机
CYutils.isIOS = function(){
    var sUserAgent = navigator.userAgent.toLowerCase();
    var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
    var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
    return bIsIpad || bIsIphoneOs;
};
/**
 * 数组对象转换
 * @param el {Array||Object}
 * @param key of obj in arr，default: id
 * @returns {Object||Array}
 * @constructor
 */
CYutils.ArrForObj = function(el,key){
    var _id = key || 'id';
    var _o = CYutils.isArray(el) ? {} : [];
    for (var k in el){
        try{
            if (CYutils.isArray(el)){
                _o[el[k][_id]] = el[k];
            }else{
                _o.push(key?el[k][_id]:el[k]);
            }
        }catch(f){
            throw('f');
        }
    }
    return _o;
};

CYutils.transtionEvent = function(){
    var t;
    var el = document.createElement('fakeelement');
    var transitions = {
        'transition':'transitionend',
        'OTransition':'oTransitionEnd',
        'MozTransition':'transitionend',
        'WebkitTransition':'webkitTransitionEnd',
        'MsTransition':'msTransitionEnd'
    };
    for(t in transitions){
        if( el.style[t] !== undefined ){
            return transitions[t];
        }
    }
};

/**
 * popup
 * @param el <xxx class="popup"></xxx>
 * @param option {position} top||center||bottom||value default:center
 * @returns {{show: initAnt, hide: destroy}}
 * example CYutils.popup('#popup', {position: 'top', onColse: function(){//do something}})
 * API show hide
 */
CYutils.popup = function (el, option) {
    var _wrap = '.popup-wrap';
    var _close = '.popup-box-close';
    var $el = $(el);
    var $elwrap = $el.find(_wrap);
    var $elclose = $el.find(_close);
    if (!$('.popup-mask').length) {
        $('body').append('<div class="popup-mask"></div>');
    }
    var $mask = $('.popup-mask');
    var op = $.extend({}, {position:'50%'}, option);
    var pos = op.position === 'center' ? '50%'
        : op.position === 'top' ? '0%'
            : op.position === 'bottom' ? '90%'
                : op.position;
    /**
     * 计算动画
     * @param str 变化的值
     * @param _dif 差值
     * @param f 加：add 减：sub 乘：mul 除：div
     * @returns {string}
     */
    var calc = function(str, _dif, f){
        var dif = _dif || 10;
        var F = f || 'add';
        var num = str.match(/(^-\d+)|(\d+)/)[0]; // 匹配正负整数
        var unit = str.match(/(^|-)|(\D+)/g)[1] || '%'; // 匹配单位
        return F === 'add' ? CYutils.Fadd(num, dif)+unit : CYutils['F'+F](num, dif)+unit;
    };
    var ani = function(el){
        var _elw = el || $elwrap;
        _elw.css({
            '-webkit-transform':'translate3d(-50%,-'+pos+',0)',
            'opacity': '1'
        });
        $mask.css({'opacity':'1'});
    };
    var initAnt = function(el, elwrap){
        var _elwrap = elwrap || $elwrap;
        var _el = el || $el;
        _elwrap.css({
            'display':'none',
            'position':'absolute',
            'top':pos,
            'left':'50%',
            '-webkit-transition':'all .2s ease-in-out',
            '-webkit-transform':'translate3d(-50%,-'+calc(pos,"","sub")+',0)',
            'opacity': '0'
        });
        _el.show();
        $mask.css({'opacity':'0','-webkit-transition':'all .2s ease-in-out'}).show();
        _elwrap.css({'display':''});
        setTimeout(function(){
            ani();
        },100);
    };
    var destroy = function(el, elwrap){
        var _elwrap = elwrap || $elwrap;
        var _el = el || $el;
        _elwrap.css({
            '-webkit-transition':'all .2s ease-in-out',
            '-webkit-transform':'translate3d(-50%,-'+calc(pos, "", "add")+',0)',
            'opacity': '0'
        });
        $mask.css({'opacity':'0'});
        setTimeout(function(){
            _el.hide();
            $mask.css({'display':'none'});
        },200);
    };
    $el.not($elwrap).click(function(event){
        if(event.target.className !== $el.attr('class')) return;
        if(CYutils.isFunction(op.onClose)){
            op.onClose();
        } else {
            destroy();
        }
    });
    $elclose.on('click', function(){
        if(CYutils.isFunction(op.onClose)){
            op.onClose();
        } else {
            destroy();
        }
    });
    return {
        show: initAnt,
        hide: destroy
    }
};
/**
 * dialog
 * @param content {Object}($DOM)||{String}
 * @param op
 * example: CYutils.dialog(['提示','提示内容'],{options})
 */
CYutils.dialog = function (content,op) {
    var _content = '';
    var _title = '';
    if(CYutils.isArray(content)){
        _title = content[0];
        _content = content[1];
    }else{
        _content = content;
    }
    var transEvent = CYutils.transtionEvent();
    var options = {
        confirm: true, //是否显示确定 (默认显示)
        confirmColor: '#FF5A5F', //确认按钮颜色
        confirmText: '确定', //确定文字
        cancel: false,  //是否显示取消 (默认隐藏)
        cancelColor: '#999',    //取消按钮颜色
        cancelText: '取消', //取消文字
        onCancel: null, //取消回调
        onConfirm: null //确定回调
    };
    options = $.extend({},options,op);
    var cancelBtn = options.cancel ? '<button class="dialog-btn-cancel dialogCancelBtn" style="color:'+ options.cancelColor +'">'+options.cancelText+'</button>' : '',
        confirmBtn = options.confirm ? '<button class="dialog-btn-confirm dialogConfirmBtn" style="color:'+ options.confirmColor +'">'+options.confirmText+'</button>' : '',
        dialogBtn = options.confirm || options.cancel ? '<div class="dialog-btn">' + cancelBtn + confirmBtn + '</div>' : '',
        title = !!_title?'<div class="dialog-title">'+ _title +'</div>':'',
        template = '<div class="dialog-bg dialogBg">'
            + '<div class="dialog-frame dialogFrame">'
            + title
            + '<div class="dialog-content" style="padding:10px 10px;">'+ _content +'</div>'
            + dialogBtn
            + '</div>'
            + '</div>';
    template = CYutils.isObject(_content)?_content:template;
    $('body').append(template);
    var $dial = $('.dialogBg,.dialogFrame');
    setTimeout(function () {
        $dial.addClass('dialog-show-up');
    }, 100);
    $('.dialogCancelBtn').click(function () {
        try{options.onCancel();}catch(e){}
        closeDialog();
    });
    $('.dialogConfirmBtn').click(function () {
        try{options.onConfirm();}catch(e){}
        closeDialog();
    });
    var closeDialog = function () {
        $dial.on(transEvent,removeAll);
        $dial.removeClass('dialog-show-up');
    };
    var removeAll = function () {
        $dial.remove();
        $dial.off(transEvent);
    }
};

/**
 * toast
 * @param content {String}
 * @param dur {Number}
 * @param type {String} ['success','info','warning','danger']
 * dur <==> type
 */
CYutils.toast = function (content,dur,type) {
    var _arr = ['success','info','warning','danger'];
    var _content = content;
    var _dur = CYutils.isNumber(dur)
        ? dur : CYutils.isNumber(type)
            ? type :3000;
    var _type = CYutils.isString(dur)&&_arr.indexOf(dur)!==-1
        ? ' toast-'+dur : CYutils.isString(type)&&_arr.indexOf(type)!==-1
            ? ' toast-'+type : ' toast-info';
    var $toastWrap = $('#toastWrap').length ? $('#toastWrap') : $('<div class="toast" id="toastWrap"></div>');
    var $toast = $('<div class="toast-content'+_type+'">'+_content+'</div>');
    $toastWrap.append($toast);
    !$('#toastWrap').length && $('body').append($toastWrap);
    setTimeout(function () {
        $toast.css({'-webkit-transform':'translate(-50%,-20%)','opacity':'0'});
        setTimeout(function(){
            $toast.remove();
            !$toastWrap.find('.toast-content').length && $toastWrap.remove();
        }, 150);
    }, _dur);
    $toast.css({'-webkit-transform':'translate(-50%,20%)'});
    setTimeout(function () {
        $toast.css({'-webkit-transform':'translate(-50%,0)','opacity':'1'});
    },150);
};


/**
 *
 * @param pages
 * @returns {methods}
 * setPath(obj) obj.page: hash
 */
CYutils.router = function(pages){
    var _entry = CYutils.getUrlParam('entry');
    if (_entry && pages[_entry]) {
        var _param = CYutils.querystring.parse();
        var _hash = _param.entry;
        delete _param.entry;
        var _curPath = location.pathname;
        window.location.replace(_curPath + '#' + _hash + (Object.keys(_param).length?'?'+ CYutils.querystring.stringify(_param):''));
        return
    }
    var main = '';
    var store = {};
    var pagesObj = {};
    var isBack = false;
    for(var x in pages){
        if(pages[x].main) main = x;
        pagesObj[x] = pages[x];
        pagesObj[x].fn = eval('new ' + pagesObj[x].fnName + '()');
    }
    var state = 0; //状态 (0:静态,1:前进,2:后退)
    var hashRoute = {pre: '', cur: '', next: ''};

    //获取Dom对象
    var getDom = function(el){
        return document.getElementById(el);
    };
    //获取hash
    var getPath = function(){
        return location.hash.replace('#','');
    };
    //获取hash page
    var getHashPath = function(str){
        var _str = str||getPath();
        var _last = _str.indexOf('?')<0?_str.length+1:_str.indexOf('?');
        return _str.substr(0,_last);
    };
    //url.share_page转换hash
    var rePathUrl = function(str){
        var _page = CYutils.getUrlParam('share_page');
        _page = !_page?'':_page;
        var _regx = new RegExp('[?|&]share_page='+_page,'i');
        var _search = str.replace(_regx,'').substr(1);
        _search = !_search ?_search :'#'+_page+'?'+_search ; //search空，取main
        return location.origin+location.pathname+_search;
    };
    // 中断所有ajax请求
    var abortRequest = function () {
        try {
            for (var i in CYutils.pendingRequests) {
                CYutils.pendingRequests[i].abort();
            }
        }catch(f){}
    };
    //执行函数
    var runFn = function(_cur, $new){
        switch(state){
            case 0: //静态
                pagesObj[_cur].fn[pagesObj[_cur].init]();
                break;
            case 1: //前进
                //调用销毁方法
                abortRequest();
                if(pagesObj[hashRoute.pre].fn.dispose) pagesObj[hashRoute.pre].fn.dispose();
                //是否缓存
                if(pagesObj[_cur].cache){
                    if(!$new.innerHTML){
                        pagesObj[_cur].fn = eval('new ' + pagesObj[_cur].fnName + '()');
                        pagesObj[_cur].fn[pagesObj[_cur].init]();
                    }else{
                        pagesObj[_cur].fn[pagesObj[_cur].reInit]();
                    }
                }else{
                    pagesObj[_cur].fn = eval('new ' + pagesObj[_cur].fnName + '()');
                    pagesObj[_cur].fn[pagesObj[_cur].init]();
                }
                break;
            case 2: //后退
                //调用销毁方法
                abortRequest();
                if(pagesObj[hashRoute.next].fn.dispose) pagesObj[hashRoute.next].fn.dispose();
                if(pagesObj[_cur].cache){
                    if (!$new.innerHTML) {
                        pagesObj[_cur].fn = eval('new ' + pagesObj[_cur].fnName + '()');
                        pagesObj[_cur].fn[pagesObj[_cur].init]();
                    }else{
                        pagesObj[_cur].fn[pagesObj[_cur].reInit]();
                    }
                }else{
                    pagesObj[_cur].fn = eval('new ' + pagesObj[_cur].fnName + '()');
                    pagesObj[_cur].fn[pagesObj[_cur].init]();
                }
                break;
            default: break;
        }
    };
    //切换页面
    var animate = function(elCur,elOld){
        var _time1 = 50;
        var _time2 = 300;
        if(!pagesObj[hashRoute.cur].animate){
            _time1 = 0;
            _time2 = 0;
        }
        var clearStyle = function(el){
            var _per = ['position','zIndex','left','top','width','height','opacity','transform','transition','transitionDelay','transitionDuration','transitionProperty','transitionTimingFunction'];
            for(var i=0;i<_per.length;i++){
                el.style[_per[i]] = '';
            }
        };
        switch(state){
            case 0: //静态
                elCur.style.display = '';
                break;
            case 1: //前进
                jQuery(elOld).css({'position':'absolute','z-index':'1','left':'0','top':'0','width':'100%','height':'100vh','opacity':'1','-webkit-transform':'translate3d(0,0,0)'});
                jQuery(elCur).css({'position':'absolute','z-index':'2','left':'0','top':'0','width':'100%','height':'100vh','opacity':'1','-webkit-transform':'translate3d(100%,0,0)'});
                elCur.style.display = '';
                setTimeout(function(){
                    jQuery(elOld).css({'-webkit-transition':'all .2s ease-in-out','opacity':'1','-webkit-transform':'translate3d(-100%,0,0)'});
                    jQuery(elCur).css({'-webkit-transition':'all .2s ease-in-out','opacity':'1','-webkit-transform':'translate3d(0,0,0)'});
                    setTimeout(function(){
                        jQuery(elOld).remove();
                        clearStyle(elCur);
                    },_time2);
                },_time1);
                break;
            case 2: //后退
                jQuery(elOld).css({'position':'absolute','z-index':'1','left':'0','top':'0','width':'100%','height':'100vh','opacity':'1','-webkit-transform':'translate3d(0,0,0)'});
                jQuery(elCur).css({'position':'absolute','z-index':'2','left':'0','top':'0','width':'100%','height':'100vh','opacity':'1','-webkit-transform':'translate3d(-100%,0,0)'});
                elCur.style.display = '';
                setTimeout(function(){
                    jQuery(elOld).css({'-webkit-transition':'all .2s ease-in-out','opacity':'1','-webkit-transform':'translate3d(100%,0,0)'});
                    jQuery(elCur).css({'-webkit-transition':'all .2s ease-in-out','opacity':'1','-webkit-transform':'translate3d(0,0,0)'});
                    setTimeout(function(){
                        jQuery(elOld).remove();
                        clearStyle(elCur);
                    },_time2);
                },_time1);
                break;
            default: break;
        }
    };
    //渲染
    var render = function(){
        //创建dom
        var _cur;
        var $new = document.createElement("div");
        $new.style.display = 'none';
        $new.id = pagesObj[hashRoute.cur].fnName;
        var $old = null;
        switch(state){
            case 0: //静态
                _cur = !!getHashPath()?getHashPath():main;
                document.body.appendChild($new);
                runFn(_cur, $new);
                break;
            case 1: //前进
                _cur = hashRoute.cur;
                $old = getDom(pagesObj[hashRoute.pre].fnName);
                $new.innerHTML = pagesObj[_cur].html;
                document.body.appendChild($new);
                runFn(_cur, $new); // 业务逻辑代码初始化|重置|销毁
                break;
            case 2: //后退
                _cur = hashRoute.cur;
                $old = getDom(pagesObj[hashRoute.next].fnName);
                $new.innerHTML = pagesObj[_cur].html;
                document.body.appendChild($new);
                runFn(_cur, $new); // 业务逻辑代码初始化|重置|销毁
                break;
            default: break;
        }
        animate($new,$old);
    };
    //缓存
    var cacheHtml = function(){
        switch(state){
            case 0: //新页面
                break;
            case 1: //前进
                var _pre = hashRoute.pre;
                try { jQuery('body>*:not(#' + pagesObj[_pre].fnName + ')').remove(); } catch (f) { }
                try{jQuery('.dropload-down').remove();}catch(f){}
                // try{pagesObj[_pre].fn.$noData.remove();}catch(f){}
                if(pagesObj[_pre].cache){
                    pagesObj[_pre].html = getDom(_pre).innerHTML;
                }else{
                    pagesObj[_pre].html = '';
                }
                break;
            case 2: //后退
                var _next = hashRoute.next;
                try { jQuery('body>*:not(#' + pagesObj[_next].fnName + ')').remove(); } catch (f) { }
                try{jQuery('.dropload-down').remove();}catch(f){}
                // try{pagesObj[_next].fn.$noData.remove();}catch(f){}
                // if(pagesObj[_next].cache){
                //     pagesObj[_next].html = getDom(_next).innerHTML;
                // }else{
                    pagesObj[_next].html = '';
                // }
                break;
            default:break;
        }
        render();
    };
    var hashFn = function(e){
        // console.log(e);
        var initParam = CYutils.getUrlParam('share_page'); //是否有分享
        if(!hashRoute.pre&&!hashRoute.cur&&!hashRoute.next){ //第一次进入
            state = 0;
            if(!!initParam){ //如果是分享的
                window.location.replace(rePathUrl(location.search));
                return;
            }
            //第一次载入是否存在hash
            if(getPath()){
                hashRoute.cur = getHashPath();
            }else{
                hashRoute.cur = main;
            }
        }
        else if(!hashRoute.next&&!!hashRoute.pre&&!isBack){ //+1 前进
            state = 1;
            isBack = true;
        }else{ //-1 后退
            state = 2;
            hashRoute.pre = '';
            hashRoute.next = hashRoute.cur;
            hashRoute.cur = getPath()?getHashPath():main;
            isBack = true;
        }
        document.title = pagesObj[hashRoute.cur].title;
        // console.log(pagesObj);
        cacheHtml();
    };
    hashFn();

    /**
     * 前进
     * @param opt
     */
    var methods = function(){
        return this;
    };
    /**
     * API
     * @type {{setPath: setPath, replacePath: replacePath, setData: setData}}
     */
    methods.prototype = {
        // 添加到浏览器访问历史的栈顶
        setPath: function (opt) {
            var _opt = jQuery.extend({}, {isBack:false}, opt);
            if(getHashPath()===_opt.page) return;
            if (/^[\/|http]/i.test(_opt.page)) {
                window.location.href = _opt.page;
                return;
            }
            hashRoute = {
                pre: getPath()===''?main:getHashPath(),
                cur: getHashPath(_opt.page),
                next: ''
            };
            isBack = _opt.isBack;
            if(opt.propData) this.setData(opt.data);
            window.location.hash = _opt.page;
        },
        // 替换掉当前的路由
        replacePath: function (opt) {
            var _opt = jQuery.extend({}, {isBack:false}, opt);
            if(getHashPath()===_opt.page) return;
            hashRoute = {
                pre: getPath()===''?main:getHashPath(),
                cur: getHashPath(_opt.page),
                next: ''
            };
            isBack = _opt.isBack;
            window.location.replace(window.location.origin+window.location.pathname+'#'+opt.page);
        },
        /**
         * 缓存数据
         * @param data
         */
        setData: function(data){
            pagesObj[hashRoute.cur].propData = data;
        }
    };

    window.addEventListener('hashchange',hashFn,false);
    return new methods();
};

/**
 * cookie管理
 * expires => new Date()
 **/
CYutils.cookie = {
    getExpiresDate:function(days, hours, minutes) {
        var ExpiresDate = new Date();
        if (typeof days == "number" && typeof hours == "number" &&
            typeof hours == "number") {
            ExpiresDate.setDate(ExpiresDate.getDate() + parseInt(days));
            ExpiresDate.setHours(ExpiresDate.getHours() + parseInt(hours));
            ExpiresDate.setMinutes(ExpiresDate.getMinutes() + parseInt(minutes));
            return ExpiresDate.toGMTString();
        }
    },
    _getValue:function(offset) {
        var endstr = document.cookie.indexOf (";", offset);
        if (endstr == -1) {
            endstr = document.cookie.length;
        }
        return unescape(document.cookie.substring(offset, endstr));
    },
    get:function(name) {
        var arg = name + "=";
        var alen = arg.length;
        var clen = document.cookie.length;
        var i = 0;
        while (i < clen) {
            var j = i + alen;
            if (document.cookie.substring(i, j) == arg) {
                return this._getValue(j);
            }
            i = document.cookie.indexOf(" ", i) + 1;
            if (i == 0) break;
        }
        return "";
    },
    set:function(name, value, expires, path, domain, secure) {
        // var strsec = this.getsec(expires);
        var exp = new Date(expires);
        exp.setTime(exp.getTime());
        document.cookie = name + "=" + escape (value) +
            ((expires) ? "; expires=" + exp.toGMTString() : "") +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            ((secure) ? "; secure" : "");
    },
    getsec:function(str){
        var str1=str.substring(1,str.length)*1;
        var str2=str.substring(0,1);
        if (str2=="s"){
            return str1*1000;
        }else if (str2=="h"){
            return str1*60*60*1000;
        }else if (str2=="d"){
            return str1*24*60*60*1000;
        }
    },
    remove:function(name,path,domain) {
        if (this.get(name)) {
            document.cookie = name + "=" +
                ((path) ? "; path=" + path : "") +
                ((domain) ? "; domain=" + domain : "") +
                "; expires=Thu, 01-Jan-70 00:00:01 GMT";
        }
    },
    clear:function(){
        var cookies = document.cookie.split(';');
        for(var i=0; i < cookies.length; i++)
            var cookieName = cookies[i].split('=')[0];
        if(cookieName=='ProductListIds')
        {
            this.remove(cookieName);
        }
    }
};

/**
 *
 * @param _obj
 */
CYutils.wxShare = function(_obj){
    var obj = $.extend({},{title:'',desc:'',link:'',imgUrl:''},_obj);
    if(!wx){
        var tag = document.createElement('script');
        tag.src = '/app/weixinjsbridge/?inajax=1&url='+encodeURIComponent(obj.link)+'&jsonpcallback=getShareJS';
        document.head.appendChild(tag);
        document.head.removeChild(tag);
    }
    var _http = /^http/.test(obj.link) ? '' : location.protocol+'//'+location.host;
    var _httpImg = /^http/.test(obj.imgUrl) ? '' : location.protocol+'//'+location.host;
    var _link = _http+obj.link;
    var _imgUrl = _httpImg+obj.imgUrl;
    var shareObj = this.shareData = {
        title:obj.title,
        desc:obj.desc,
        link:_link,
        imgUrl:_imgUrl
    };
    var shareObjTimeline = {
        title:obj.title,
        link:_link,
        imgUrl:_imgUrl
    };
    wx&&wx.ready(function() {
        wx.onMenuShareTimeline(shareObjTimeline);
        wx.onMenuShareAppMessage(shareObj);
        wx.onMenuShareQQ(shareObj);
        wx.onMenuShareWeibo(shareObj);
        wx.onMenuShareQZone(shareObj);
    });
};

// CYutils.wxChooseWXPay = function(_obj){
//     var obj = $.extend({},{title:'',desc:'',link:'',imgUrl:''},_obj);
//     if(!wx){
//         var tag = document.createElement('script');
//         tag.src = '/app/weixinjsbridge/?inajax=1&url='+encodeURIComponent(obj.link)+'&jsonpcallback=getShareJS';
//         document.head.appendChild(tag);
//         document.head.removeChild(tag);
//     }
//     var _http = /^http/.test(obj.link) ? '' : location.protocol+'//'+location.host;
//     var _httpImg = /^http/.test(obj.imgUrl) ? '' : location.protocol+'//'+location.host;
//     var _link = _http+obj.link;
//     var _imgUrl = _httpImg+obj.imgUrl;
//     var shareObj = this.shareData = {
//         title:obj.title,
//         desc:obj.desc,
//         link:_link,
//         imgUrl:_imgUrl
//     };
//     var shareObjTimeline = {
//         title:obj.title,
//         link:_link,
//         imgUrl:_imgUrl
//     };
//     wx&&wx.ready(function() {
//         wx.onMenuShareTimeline(shareObjTimeline);
//         wx.onMenuShareAppMessage(shareObj);
//         wx.onMenuShareQQ(shareObj);
//         wx.onMenuShareWeibo(shareObj);
//         wx.onMenuShareQZone(shareObj);
//     });
// };

CYutils.appCall = function(method,param){
    var params = $.extend({},param);
    params = CYutils.isObject(params.params)?params:{};
    if(CYutils.isApp()){
        if(CYutils.isAndroid()){
            Object.keys(params).length?Android[method](Object.values(params).join(',')):Android[method]();
        }else if(CYutils.isIOS()){
            params['Foo'] = method;
            if(!bridge){
                document.addEventListener('WebViewJavascriptBridgeReady', function(event) {
                    bridge = event.bridge;
                    bridge.send(params);
                }, false);
            } else {
                bridge.send(params);
            }
        }
    } else if(CYutils.isWeiXin()){
        CYutils.isFunction(param.wxCallback)&&param.wxCallback();
    } else {
        if (CYutils.isFunction(param.browserCallback)) {
            param.browserCallback();
        } else {
            CYutils.toast('请使用微信或兴隆大院App访问');
        }
    }
};

/**
 * 绑定 data-href 跳转
 */
CYutils.bindHref = function(){
    $('body').on('click','[data-href]',function(){
        var _href = this.dataset.href;
        if (!$.trim(_href)) return;
        window.location.href = _href;
    });
};